package com.yiyue.graduate.controller;

import com.yiyue.graduate.pojo.Course;
import com.yiyue.graduate.pojo.User;
import com.yiyue.graduate.service.CourseService;
import com.yiyue.graduate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @author yiyuexiaofusheng
 */
@Controller
public class IndexController {

   @Autowired
   CourseService courseService;
   @Autowired
   UserService userService;
//    @PostMapping("/login")
//    public String mainPage(User course1, Model model, HttpSession session){
//        String loginName = course1.getLoginName();
//        String loginPwd = course1.getLoginPwd();
//        if (StringUtils.hasLength(loginName)&&StringUtils.hasLength(loginPwd)){
//            User courseUser = userService.courseUserMapper(loginName, loginPwd);
//            if(courseUser!=null) {
//                session.setAttribute("loginName",courseUser.getLoginName());
//                return "admin/user";
//            }else{
//                return "login";
//            }
//        }else{
//            return "login";
//        }
//    }
//    /**
//     * 防止再刷新重定向
//     */
//    @GetMapping("/main.html")
//    public String mainHtml(HttpSession session){
//        Object loginName = session.getAttribute("user");
//
//        return "main";
//    }
    @GetMapping(value = {"/","/index"})
    public String index(ModelMap model){
        List<Course> topCourses = courseService.queryTopCourse();
        List<Course> freeCourses = courseService.queryFreeCourse();
        List<Course> majorCourse = courseService.queryMajorCourse();
        model.addAttribute("topCourse",topCourses);
        model.addAttribute("freeCourses",freeCourses);
        model.addAttribute("majorCourse",majorCourse);

        return "index";
    }


    @GetMapping("/toLogin")
    public String loginIndex(){
        return "login";
    }

    @GetMapping("/toRegister")
    public String registerIndex(){
        return "register";
    }

    @PostMapping("/login")
    public String login(User courseUser, HttpSession session, Model model){
        User userLogin = userService.userLogin(courseUser);
        if(userLogin != null){
            session.setAttribute("userLogin",userLogin);
            return "redirect:/index";
        }
        return "redirect:/toLogin";
    }

    @PostMapping("/register")
    public String register(){
        return "redirect:/toLogin";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("userLogin");
        return "redirect:/index";
    }
}
